const app = getApp();
Page({
  data: {
    codes: [],
    filteredCodes: [], // 筛选后的数据

    searchType: '', // 当前选中的搜索类型
    searchTypeIndex: 0,
    searchTypeLabel: '',

    selectedType: '', // 创建时选择的类型
    selectedTypeIndex: 0,
    selectedTypeLabel: '',

    dialogVisible: false,

    pickerRange: [
      { label: '用户激活码', value: 'ACTIVATION' },
      { label: '普通级别验证码', value: 'SUBMIT_ORDER' },
      { label: '高级级别验证码', value: 'SUPER_SUBMIT_ORDER' }
    ],

    typeMap: {
      ACTIVATION: '用户激活码',
      SUBMIT_ORDER: '普通级别验证码',
      SUPER_SUBMIT_ORDER: '高级级别验证码'
    }
  },

  onLoad() {

    this.startPolling(); // 每4秒刷新一次数据
  },

  onUnload() {
    clearInterval(this.pollingInterval);
  },

  startPolling() {
    this.fetchData();
    this.pollingInterval = setInterval(() => {
      if (app.globalData.user && app.globalData.user.active) {
        this.fetchData();
      }
    }, 4000);
  },

  fetchData() {
    const params = {};
    if (this.data.searchType) {
      params.type = this.data.searchType;
    }

    const user = wx.getStorageSync('user');
    if (!user || !user.active) {
      wx.showToast({ title: '请先激活账号', icon: 'none' });
      return;
    }

    app.request({
      url: '/admin/verificationCode/getVerificationCodeList',
      data: params,
      success: res => {
        if (res.code === 1) {
          let codes = res.data;

          // 本地按 type 再次筛选（确保即使后端未过滤也能正确显示）
          if (this.data.searchType) {
            codes = codes.filter(code => code.type === this.data.searchType);
          }

          this.setData({ codes, filteredCodes: codes });
        } else {
          wx.showToast({ title: res.msg || '获取失败', icon: 'none' });
        }
      },
      fail: err => {
        console.error('请求失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  copyCode(e) {
    const code = e.currentTarget.dataset.code;
  
    wx.setClipboardData({
      data: code,
      success: () => {
        wx.showToast({ title: '复制成功', icon: 'success' });
      },
      fail: () => {
        wx.showToast({ title: '复制失败', icon: 'none' });
      }
    });
  },
  onPickerChange(e) {
    const index = e.detail.value;
    const option = this.data.pickerRange[index];
    this.setData({
      searchTypeIndex: index,
      searchType: option.value,
      searchTypeLabel: option.label
    });
    this.fetchData();
  },

  onCreatePickerChange(e) {
    const index = e.detail.value;
    const option = this.data.pickerRange[index];
    this.setData({
      selectedTypeIndex: index,
      selectedType: option.value,
      selectedTypeLabel: option.label
    });
  },

  showDialog() {
    this.setData({ dialogVisible: true });
  },

  closeDialog() {
    this.setData({ dialogVisible: false });
  },

  createCode() {
    if (!this.data.selectedType) {
      wx.showToast({ title: '请选择验证码类型', icon: 'none' });
      return;
    }

    app.request({
      url: '/admin/verificationCode/createCode/' + this.data.selectedType,
      method: 'POST',
      success: res => {
        if (res.code === 1) {
          wx.showToast({ title: '生成成功' });
          this.closeDialog();
          this.fetchData();
        } else {
          wx.showToast({ title: res.msg || '生成失败', icon: 'none' });
        }
      },
      fail: err => {
        wx.showToast({ title: '请求出错', icon: 'none' });
      }
    });
  },

  handleDelete(e) {
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '提示',
      content: '确定要删除该验证码吗？',
      success: res => {
        if (res.confirm) {
          app.request({
            url: '/admin/verificationCode/deleteById/' + id,
            method: 'DELETE',
            success: res => {
              if (res.code === 1) {
                wx.showToast({ title: '删除成功' });
                this.fetchData();
              } else {
                wx.showToast({ title: res.msg || '删除失败', icon: 'none' });
              }
            },
            fail: err => {
              wx.showToast({ title: '请求出错', icon: 'none' });
            }
          });
        }
      }
    });
  },

  resetSearch() {
    this.setData({
      searchType: '',
      searchTypeIndex: 0,
      searchTypeLabel: ''
    });
    this.fetchData();
  },
  goHome() {
    wx.redirectTo({
      url: '/pages/admin/AdminHomeView/AdminHomeView'
    });
  },
});